import config from "./config";

export function toast(value) {
  if (!!value) {
    uni.showToast({
      title: value,
      icon: "none",
      duration: 2000,
    });
  } else {
    uni.showLoading({
      title: "加载中",
    });
  }
}

export function base64src(base64data, cb) {
  const fsm = uni.getFileSystemManager();
  const FILE_BASE_NAME = 'tmp_qr_code'; // 自定义文件名
  const [, format, bodyData] = /data:image\/(\w+);base64,(.*)/.exec(base64data) || [];
  if (!format) {
    return (new Error('ERROR_BASE64SRC_PARSE'));
  }
  // eslint-disable-next-line no-undef
  const filePath = `${wx.env.USER_DATA_PATH}/${FILE_BASE_NAME}.${format}`;
  const buffer = uni.base64ToArrayBuffer(bodyData);
  fsm.writeFile({
    filePath,
    data: buffer,
    encoding: 'binary',
    success() {
      cb(filePath);
    },
    fail() {
      return (new Error('ERROR_BASE64SRC_WRITE'));
    }
  });
};

export function setStore(key, data) {
  uni.setStorageSync(key, data);
}
export function getStore(key) {
  return uni.getStorageSync(key);
}

export function removeStore(key) {
  uni.removeStorageSync(key);
}

export function clearStore() {
  // let isFirstHare = getStore("isFirstHare");
  let imAppKey = getStore("imAppKey");
  uni.clearStorageSync();
  // if (isFirstHare) {
  //   setStore("isFirstHare", "Y");
  // }
  setStore("imAppKey", imAppKey);

}

export function hide() {
  uni.hideToast();
}
export function hideLoad() {
  uni.hideLoading();
}

//添加就诊人-日期选择时
export function getDate(type) {
  const date = new Date();

  let year = date.getFullYear();
  let month = date.getMonth() + 1;
  let day = date.getDate();

  if (type === "start") {
    year = year - 60;
  } else if (type === "end") {
    year = year + 2;
  }
  month = month > 9 ? month : "0" + month;
  day = day > 9 ? day : "0" + day;

  return `${year}-${month}-${day}`;
}

//图片上传地址...
export function fileUpload() {
  return `${config.host}/sys/upload/fileUpload`;
}

export function initTime(datetime) {
  datetime = new Date(datetime);
  let oneDayms = 86400000;
  let now = new Date().getTime();
  let diff = datetime - now;

  let year = datetime.getFullYear();
  let simpleYear = datetime.getYear() - 100;
  let month = datetime.getMonth() + 1;
  month = month > 9 ? month : "0" + month;
  let day = datetime.getDate();
  day = day > 9 ? day : "0" + day;
  let hour = datetime.getHours();
  hour = hour > 9 ? hour : "0" + hour;
  let min = datetime.getMinutes();
  min = min > 9 ? min : "0" + min;
  if (diff >= oneDayms) {
    return `${month}-${day}`;
  } else {
    return `${hour}:${min}`;
  }
}
export function validateIdCard(val) {
  if (checkCode(val)) {
    var date = val.substring(6, 14);
    if (checkDate(date)) {
      if (checkProv(val.substring(0, 2))) {
        return true;
      }
    }
  }
  return false;
}
export function checkCode(val) {
  var p = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
  var factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
  var parity = [1, 0, "X", 9, 8, 7, 6, 5, 4, 3, 2];
  var code = val.substring(17);
  if (p.test(val)) {
    var sum = 0;
    for (var i = 0; i < 17; i++) {
      sum += val[i] * factor[i];
    }
    if (parity[sum % 11] == code.toUpperCase()) {
      return true;
    }
  }
  return false;
}
export function checkDate(val) {
  var pattern = /^(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)$/;
  if (pattern.test(val)) {
    var year = val.substring(0, 4);
    var month = val.substring(4, 6);
    var date = val.substring(6, 8);
    var date2 = new Date(year + "-" + month + "-" + date);
    if (date2 && date2.getMonth() == parseInt(month) - 1) {
      return true;
    }
  }
  return false;
}
export function checkProv(val) {
  var pattern = /^[1-9][0-9]/;
  var provs = {
    11: "北京",
    12: "天津",
    13: "河北",
    14: "山西",
    15: "内蒙古",
    21: "辽宁",
    22: "吉林",
    23: "黑龙江 ",
    31: "上海",
    32: "江苏",
    33: "浙江",
    34: "安徽",
    35: "福建",
    36: "江西",
    37: "山东",
    41: "河南",
    42: "湖北 ",
    43: "湖南",
    44: "广东",
    45: "广西",
    46: "海南",
    50: "重庆",
    51: "四川",
    52: "贵州",
    53: "云南",
    54: "西藏 ",
    61: "陕西",
    62: "甘肃",
    63: "青海",
    64: "宁夏",
    65: "新疆",
    71: "台湾",
    81: "香港",
    82: "澳门",
  };
  if (pattern.test(val)) {
    if (provs[val]) {
      return true;
    }
  }
  return false;
}
// 版本对比  兼容
export function compareVersion(v1, v2) {
  v1 = v1.split(".");
  v2 = v2.split(".");
  const len = Math.max(v1.length, v2.length);

  while (v1.length < len) {
    v1.push("0");
  }
  while (v2.length < len) {
    v2.push("0");
  }

  for (let i = 0; i < len; i++) {
    const num1 = parseInt(v1[i]);
    const num2 = parseInt(v2[i]);

    if (num1 > num2) {
      return 1;
    } else if (num1 < num2) {
      return -1;
    }
  }

  return 0;
}

/**
 *获取未来七天日期
 getDay（7）
 * @param {*} day  为第几天的;
 */
export function getDay(day) {
  var today = new Date();
  var targetday_milliseconds = today.getTime() + 1000 * 60 * 60 * 24 * day;
  today.setTime(targetday_milliseconds); //注意，这行是关键代码
  var tYear = today.getFullYear();
  var tMonth = today.getMonth();
  var tDate = today.getDate();
  tMonth = doHandleMonth(tMonth + 1);
  tDate = doHandleMonth(tDate);
  // return tYear + "-" + tMonth + "-" + tDate;
  let tiem = {
    tYear,
    tMonth,
    tDate,
  };
  return tiem;
}

export function doHandleMonth(month) {
  var m = month;
  if (month.toString().length == 1) {
    m = "0" + month;
  }
  return m;
}

export const timest = () => {
  let tmp = Date.parse(new Date()).toString();
  tmp = tmp.substr(0, 10);
  return Number(tmp);
};

/**
 * 节流原理：在一定时间内，只能触发一次
 *
 * @param {Function} func 要执行的回调函数
 * @param {Number} wait 延时的时间
 * @param {Boolean} immediate 是否立即执行
 * @return null
 */
let throttleFTimer;
let throttleFlag;
export const throttle = (func, wait = 500, immediate = true) => {
  if (immediate) {
    if (!throttleFlag) {
      throttleFlag = true
      // 如果是立即执行，则在wait毫秒内开始时执行
      typeof func === 'function' && func()
      throttleFTimer = setTimeout(() => {
        throttleFlag = false
      }, wait)
    }
  } else if (!throttleFlag) {
    throttleFlag = true
    // 如果是非立即执行，则在wait毫秒内的结束处执行
    throttleFTimer = setTimeout(() => {
      throttleFlag = false
      typeof func === 'function' && func()
    }, wait)
  }
}

/**
 * 防抖原理：一定时间内，只有最后一次操作，再过wait毫秒后才执行函数
 *
 * @param {Function} func 要执行的回调函数
 * @param {Number} wait 延时的时间
 * @param {Boolean} immediate 是否立即执行
 * @return null
 */
let debounceTimeout = null
export const debounce = (func, wait = 500, immediate = false) => {
  // 清除定时器
  if (debounceTimeout !== null) clearTimeout(debounceTimeout)
  // 立即执行，此类情况一般用不到
  if (immediate) {
    const callNow = !debounceTimeout
    debounceTimeout = setTimeout(() => {
      debounceTimeout = null
    }, wait)
    if (callNow) typeof func === 'function' && func()
  } else {
    // 设置定时器，当最后一次操作后，timeout不会再被清除，所以在延时wait毫秒后执行func回调方法
    debounceTimeout = setTimeout(() => {
      typeof func === 'function' && func()
    }, wait)
  }
}
/**
 * 字符串转对象
 *
 * @param {String} str 要执行的参数
 * @return null
 */
export const strTransferObj = (str) => {
  let arr = str.split('&')
  let obj = {}
  arr.map(item => {
    obj[item.split('=')[0]] = item.split('=')[1]
  })
  return obj
}

/**
   * 密码复杂性
   * @returns {}
   */
export function checkPassword(newPass) {
  var regUpper = /[A-Z]/;
  var regLower = /[a-z]/;
  var regNum = /[0-9]/;
  var regTeShu = new RegExp("[`~!@#$^&*()=|{}':;',\\[\\].<>/?~！@#￥……&*（）——|{}【】‘；：”“'。，、？+-]");
  var complex = 0;
  let result = {};//返回结果
  if (regLower.test(newPass)) {
    ++complex;
  }
  if (regUpper.test(newPass)) {
    ++complex;
  }
  if (regNum.test(newPass)) {
    ++complex;
  }
  if (regTeShu.test(newPass)) {
    ++complex;
  }
  if (complex < 3) {
    result.status = 0
    result.message = '密码必须包含数字、字母大、小写、符号至少3种';
    return result;
  }
  if (newPass.length < 8) {
    result.status = 0
    result.message = '密码长度不小于8位';
    return result;
  }
  result.status = 1;
  return result;
}

/**
 * @desc 页面返回实例带参
 * @param {参数名称} key 
 * @param {参数值} value 
 */
export const backPrevPage = (key, value) => {
  const pages = getCurrentPages();
  if (!pages) {
    uni.showToast({
      title: '页面不存在',
      icon: "none",
      duration: 2000,
    });
    return
  }
  const prve = pages[pages.length - 2];
  prve.$vm[key] = value
  uni.navigateBack({
    delta: 1
  })
}
/**
 * @desc 与backPrevPage对应，获取参数方法
 * @param {参数名称} key
 */
export const getPageParams = (key) => {
  const pages = getCurrentPages();
  const curPage = pages[pages.length - 1];
  const pageData = curPage.$vm[key]
  if (!pageData) return
  return pageData
}
/**
 * @desc 清除页面实例参数
 */
export const deletePageParams = (key) => {
  const pages = getCurrentPages();
  const curPage = pages[pages.length - 1];
  delete curPage.$vm[key]
}